<?php
/**
 * 类名称
 * User: 13651
 * Time: 2025/9/28 15:26
 */

namespace App\Services;

use App\Api\Controllers\LeshuaUnion\LeshuaBaseController as LeshuaUnion;
use App\Common\ResponseCode;
use App\Exceptions\BizException;
use App\Exceptions\BusinessException;
use App\Extensions\BaseService;
use App\Param\LeshuaUnion\GetQrocdeParam;
use App\Repository\LeshuaUnionStoresRepo;
use App\Repository\StorePayRepo;
use Illuminate\Support\Facades\Log;
use App\Traits\ResponseTrait;
class LeshuaUnionCommonService   extends BaseService
{
    use ResponseTrait;

    /**
     * 获取实名认证二维码
     * @param GetQrocdeParam $param
     * @return string
     * @throws BizException
     */
    public function getQrcodeImgService(GetQrocdeParam $param)
    {

        /**
         * 校验支付渠道参数
         */
        $company = [
            'leshuaunion'
        ];
        if (!in_array($param->getCompany(), $company))
            return $this->errorResponse('当前通道暂不支持');

        /**
         * 获取该商户是否开通成功
         */
        $res = StorePayRepo::getInstance()->getByStoreIdStatusInfo($param->getStoreId(),$param->getCompany());
        if ($res->isEmpty())
            return $this->errorResponse('支付渠道信息未配置');

        $data = $res->toArray();
        if (count($data)!=3)
            return $this->errorResponse('支付渠道信息不正确');

        /**
         * 乐刷侧的实名认证二维码是临时的有时效
         */
        if ($param->getCompany() == 'leshuaunion')
        {
            /**
             * 获取渠道配置信息
             */
            $leshuConfigInfo = LeshuaUnionConfigService::getInstance()->getByConfigIdService(1234);
            if (empty($leshuConfigInfo))
                return $this->errorResponse('乐刷渠道信息未配置');

            /**
             * 获取乐刷侧商户编号
             */
            $info = LeshuaUnionStoresRepo::getInstance()->getByStoreId($param->getStoreId());
            if (empty($info))
                return $this->errorResponse('未开通该渠道');

            /**
             * 获取二维码
             */
            if ($info->status == 1)
            {
                return $this->leshuaCreateQrcode($leshuConfigInfo,$info,$param->getStoreId());
            }

            /**
             * 获取子商户号
             */
            if ($info->status == 2)
            {

                return $this->getLeshuaSubMchQuery($leshuConfigInfo,$info);
            }

            /**
             * 获取授权状态
             */
            if ($info->status == 3)
            {
                return $this->getAuthInfo($leshuConfigInfo,$info);
            }
        }

    }

    /**
     * 乐刷认证二维码
     * @param $leshuConfigInfo
     * @param $info
     * @param $store_id
     * @return array|string
     * @throws BizException
     */
    protected function leshuaCreateQrcode($leshuConfigInfo,$info,$store_id)
    {

        /**
         * 组装请求参数
         */
        $leshuaConfig = [
            'orgId'=>$leshuConfigInfo->orgId,
            'key'=>$leshuConfigInfo->key,
        ];

        $data =[
            'merchantId'=>$info->mch_id,
        ];
        $wechatResult = LeshuaUnion::getInstance()->subjectApply($leshuaConfig,$data);
        Log::info('乐刷联合支付微信实名认证申请返回报文'.$wechatResult);

        if (empty($wechatResult))
            return $this->errorResponse('申请异常');

        $wechatSubjectApply = json_decode($wechatResult,true);
        if (!in_array($wechatSubjectApply['error_code'],['0','1']))//0成功 1重复发起申请
            return $this->errorResponse($wechatSubjectApply['error_msg']);

        /**
         * 支付宝实名认证申请，成功申请后乐刷侧会返回实名认证申请单号
         */
        $aliPayResult = LeshuaUnion::getInstance()->aliPayApply($leshuaConfig,$data);
        Log::info('乐刷联合支付支付宝实名认证申请返回报文'.$aliPayResult);

        if (empty($aliPayResult))
            return $this->errorResponse('申请异常');

        $aliPaySubjectApply = json_decode($aliPayResult,true);
        if (!in_array($aliPaySubjectApply['error_code'],['0','10006','10004']))
            return $this->errorResponse($aliPaySubjectApply['error_msg']);

        /**
         * wx、zfb实名认证查询,乐刷侧会返回一个临时的实名认证二维码，故该二维码不用存入数据库
         */
        $wechatQueryResult = LeshuaUnion::getInstance()->subjectQuery($leshuaConfig,$data);
        Log::info('乐刷联合支付获取微信实名认证查询返回报文'.$wechatQueryResult);

        if (empty($wechatQueryResult))
            return $this->errorResponse('请求失败');

        $wechatSubjectApplyQuery = json_decode($wechatQueryResult,true);

        if ($wechatSubjectApplyQuery['error_code']!='0')
            return $this->errorResponse($wechatSubjectApplyQuery['error_msg']);

        /**
         * 微信认证状态当applyStatus为 APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT、APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON、APPLYMENT_STATE_PASSED、APPLYMENT_STATE_FREEZED时，会返回
         */
        $applyStatus = [
            'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT',
            'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON',
            'APPLYMENT_STATE_PASSED、APPLYMENT_STATE_FREEZED'
        ];
        $wechatQrcode = '';
        if (in_array($wechatSubjectApplyQuery['data']['applyStatus'],$applyStatus))
            $wechatQrcode = $wechatSubjectApplyQuery['data']['qrcodeData'];

        /**
         * 支付实名认证查询
         */
        $alipayQueryResult = LeshuaUnion::getInstance()->alipayQueryApplyStatus($leshuaConfig,$data);
        Log::info('乐刷联合支付获取支付宝实名认证查询返回报文'.$alipayQueryResult);
        if (empty($alipayQueryResult))
            return $this->errorResponse('请求失败');

        $alipayQuery = json_decode($alipayQueryResult,true);

        if ($alipayQuery['error_code']!='0')
            return $this->errorResponse($alipayQuery['error_msg']);

        /**
         * 审核通过、审核中、已冻结时返回
         */
        $alipayStatus = [
            'AUDITING',
            'AUDIT_PASS',
            'AUDIT_FREEZE',
            'CONTACT_CONFIRM'
        ];
        $alipayQrcode = '';
        if (in_array($alipayQuery['data']['orderstatus'],$alipayStatus))
            $alipayQrcode = $alipayQuery['data']['qrcode'];

        $info->wx_remark = $wechatSubjectApplyQuery['data']['rejectReason'];
        $info->alipay_remark = empty($alipayQuery['verifyList']) ? '' : '字段'.$alipayQuery['verifyList'][0]['failParam'].$alipayQuery['verifyList'][0]['failReason'];
        $info->status = 2;
        $info->wx_qrcode = $wechatQrcode;
        $info->alipay_qrcode = $alipayQrcode;
        $info->save();
        $return = [
            'aliay_submchid'=>$info->aliay_submchid,
            'wechat_submchid'=>$info->wechat_submchid,
            'zfb_qr'=>$alipayQrcode,
            'wx_qr'=>$wechatQrcode,
            'store_qr'=>env("APP_URL") . '/qr?store_id=' . $store_id,
            'submit_status'=>$info->status,
            'wx_remark'=>$wechatSubjectApplyQuery['data']['rejectReason'],
            'alipay_remark'=>empty($alipayQuery['verifyList']) ? '' : '字段'.$alipayQuery['verifyList'][0]['failParam'].$alipayQuery['verifyList'][0]['failReason'],
        ];
        return $return;
    }


    /**
     * 获取乐刷子商户号
     */
    protected function getLeshuaSubMchQuery($leshuConfigInfo,$info)
    {
        /**
         * 组装请求参数
         */
        $leshuaConfig = [
            'orgId'=>$leshuConfigInfo->orgId,
            'key'=>$leshuConfigInfo->key,
        ];

        $data =[
            'merchantId'=>$info->mch_id,
        ];
        $dataArr = LeshuaUnion::getInstance()->subMchQuery($leshuaConfig,$data);
        Log::info('乐刷联合支付获取子商户号返回报文'.$dataArr);

        if (empty($dataArr))
            return $this->errorResponse('申请异常');

        $result  = json_decode($dataArr,true);

        /**
         * 子商户号
         * PS!未返回银联QRA商户号
         */
        $save['aliay_submchid'] = $result['data']['alipay'][0]['subMchId'];
        $save['wechat_submchid'] = $result['data']['wechat'][0]['subMchId'];
        $save['unionscan'] = $result['data']['unionscan'][0]['subMchId'];
        $save['cups'] = $result['data']['cups'][0]['subMchId'];
        $save['status'] = 3;
        $save['wx_auth_status'] = 3;
        $save['alipay_auth_status'] = 3;
        LeshuaUnionStoresRepo::getInstance()->saveDataRepo($save,$info->id);
        $wxFlag = $this->is404($info->wx_qrcode);

        $wechatQrcode = $info->wx_qrcode;
        //已过期
        if ($wxFlag || empty($info->wx_qrcode)) {
            /**
             * wx、zfb实名认证查询,乐刷侧会返回一个临时的实名认证二维码，故该二维码不用存入数据库
             */
            $wechatQueryResult = LeshuaUnion::getInstance()->subjectQuery($leshuaConfig,$data);
            Log::info('乐刷联合支付获取微信实名认证查询返回报文'.$wechatQueryResult);

            if (empty($wechatQueryResult))
                return $this->errorResponse('请求失败');

            $wechatSubjectApplyQuery = json_decode($wechatQueryResult,true);

            if ($wechatSubjectApplyQuery['error_code']!='0')
                return $this->errorResponse($wechatSubjectApplyQuery['error_msg']);

            /**
             * 微信认证状态当applyStatus为 APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT、APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON、APPLYMENT_STATE_PASSED、APPLYMENT_STATE_FREEZED时，会返回
             */
            $applyStatus = [
                'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT',
                'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON',
                'APPLYMENT_STATE_PASSED',
                'APPLYMENT_STATE_FREEZED',
            ];

            if (in_array($wechatSubjectApplyQuery['data']['applyStatus'],$applyStatus))
                $wechatQrcode = $wechatSubjectApplyQuery['data']['qrcodeData'];
            $info->wx_qrcode = $wechatQrcode;
            $info->save();
        }
        $return = [
            'aliay_submchid'=>$save['aliay_submchid'],
            'wechat_submchid'=>$save['wechat_submchid'],
            'zfb_qr'=>$info->alipay_qrcode,
            'wx_qr'=>base64_encode(file_get_contents($wechatQrcode)),
            'store_qr'=>env("APP_URL") . '/qr?store_id=' . $info->store_id,
            'submit_status'=>3,
            'wx_remark'=>'',
            'alipay_remark'=>'',
        ];
        return $return;
    }

    /**
     * 获取授权状态
     * @param $leshuConfigInfo
     * @param $info
     * @return array|string
     * @throws BizException
     */
    protected function getAuthInfo($leshuConfigInfo,$info)
    {
        /**
         * 组装请求参数
         */
        $leshuaConfig = [
            'orgId'=>$leshuConfigInfo->orgId,
            'key'=>$leshuConfigInfo->key,
        ];

        $data =[
            'merchantId'=>$info->mch_id,
        ];
        $dataArr = LeshuaUnion::getInstance()->queryAlipayMchStatus($leshuaConfig,$data);
        Log::info('乐刷联合支付获取支付宝实名认证返回报文'.$dataArr);

        if (empty($dataArr))
            return $this->errorResponse('申请异常');

        /**
         * 支付宝认证状态
         * 已授权（AUTHORIZED）
         * 未授权（UNAUTHORIZED）
         * 已销户（CLOSED）
         */
        $alipayResult  = json_decode($dataArr,true);
        $checkResult = [
            'AUTHORIZED'=>4,
            'CLOSED'=>5,
            'UNAUTHORIZED'=>5,
        ];
        $save['alipay_auth_status'] = $checkResult[$alipayResult['data']['checkResult']];

        /**
         * 获取微信授权认证状态
         */
        $wxData =[
            'wxSubMchId'=>$info->wechat_submchid,
        ];

        $wxArr = LeshuaUnion::getInstance()->getAuthorizeState($leshuaConfig,$wxData);
        Log::info('乐刷联合支付获取微信实名认证返回报文'.$wxArr);

        if (empty($wxArr))
            return $this->errorResponse('申请异常');

        $wechatResult  = json_decode($wxArr,true);

        /**
         * 枚举（中文）：已授权 未授权
         */
        $save['wx_auth_status'] = $wechatResult['data']['msg'] == '已授权' ? 4 : 5;
        LeshuaUnionStoresRepo::getInstance()->saveDataRepo($save,$info->id);

        $wxFlag = $this->is404($info->wx_qrcode);

        $wechatQrcode = $info->wx_qrcode;
        //已过期
        if ($wxFlag || empty($info->wx_qrcode)) {
            /**
             * wx、zfb实名认证查询,乐刷侧会返回一个临时的实名认证二维码，故该二维码不用存入数据库
             */
            $wechatQueryResult = LeshuaUnion::getInstance()->subjectQuery($leshuaConfig,$data);
            Log::info('乐刷联合支付获取微信实名认证查询返回报文'.$wechatQueryResult);

            if (empty($wechatQueryResult))
                return $this->errorResponse('申请异常');

            $wechatSubjectApplyQuery = json_decode($wechatQueryResult,true);

            if ($wechatSubjectApplyQuery['error_code']!='0')
                return $this->errorResponse($wechatSubjectApplyQuery['error_msg']);

            /**
             * 微信认证状态当applyStatus为 APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT、APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON、APPLYMENT_STATE_PASSED、APPLYMENT_STATE_FREEZED时，会返回
             */
            $applyStatus = [
                'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT',
                'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON',
                'APPLYMENT_STATE_PASSED',
                'APPLYMENT_STATE_FREEZED',
            ];

            if (in_array($wechatSubjectApplyQuery['data']['applyStatus'],$applyStatus))
                $wechatQrcode = $wechatSubjectApplyQuery['data']['qrcodeData'];
            $info->wx_qrcode = $wechatQrcode;
            $info->save();
        }
        $return = [
            'aliay_submchid'=>$info->aliay_submchid,
            'wechat_submchid'=>$info->wechat_submchid,
            'zfb_qr'=>$info->alipay_qrcode,
            'wx_qr'=>base64_encode(file_get_contents($wechatQrcode)),
            'store_qr'=>env("APP_URL") . '/qr?store_id=' . $info->store_id,
            'submit_status'=>3,
            'wx_remark'=>'',
            'alipay_remark'=>'',
        ];
        return $return;
    }

    /**
     * 检测链接是否为404
     * @param $url
     * @return bool
     */
    protected function is404($url) {
        $headers = @get_headers($url);
        if ($headers && preg_match('/^HTTP\/[0-9.]+ 404/', $headers[0])) {
            return true;
        }
        return false;
    }
}